// 错误处理
use std::collections::HashMap;

use tower_cookies::{Cookie, Cookies};

#[derive(Clone)]
pub enum GLOBALERROR {
    // SERVICEERROR = 4000,
    // FAILED = 4001,
    ADDFAILED = 4002,
    UPDATEFAILED = 4003,
    DELETEFAILED = 4004,
    RECORDNOTFOUND = 4005,
    PARAMINVALIDFAILED = 4006,
    UPLOADFAILED = 4007,
    SUCCESS = 200,
    ADDSUCCESS = 5002,
    UPDATESUCCESS = 5003,
    DELETESUCCESS = 5004,
    UPLOADSUCCESS = 5007,
}

pub struct XErrors {
    pub errors: HashMap<i32, String>
}

impl XErrors {
    pub fn new() -> Self {
        let mut errors = HashMap::new();
        errors.insert(4002, "添加失败".to_string());
        errors.insert(4003, "更新失败".to_string());
        errors.insert(4004, "删除失败".to_string());
        errors.insert(4005, "数据不存在".to_string());
        errors.insert(4006, "参数错误".to_string());
        errors.insert(4007, "上传失败".to_string());
        errors.insert(200, "正常".to_string());
        errors.insert(5001, "操作成功".to_string());
        errors.insert(5002, "添加成功".to_string());
        errors.insert(5003, "更新成功".to_string());
        errors.insert(5004, "删除成功".to_string());
        errors.insert(5007, "上传成功".to_string());
        Self {
            errors
        }
    }
  
    pub fn get_error(&self, code:GLOBALERROR) -> String {
        let code_num = code as i32;
        self.errors.get(&code_num).expect("未知错误").to_string()
    }

    pub fn set_cookie_error(&self, cookies: Cookies, code:GLOBALERROR, err:String) {
        let code_num = code as i32;
        let mut err_msg = self.errors.get(&code_num).expect("未知错误").to_string();
        if code_num >= 5000 {
            err_msg  = format!("_flash_success{}", err_msg);
        }
        if !err.is_empty() {
            err_msg  = format!("{}:{}", err_msg, err.to_string());
        }
        let mut cookie_msg = Cookie::new("_flash", err_msg);
        cookie_msg.set_path("/");
        cookies.add(cookie_msg);
    }
}
